package cn.faifai.web.api;

import cn.hutool.core.util.ObjectUtil;
import cn.faifai.common.component.R;
import cn.faifai.framework.utils.fetcher.SidFetcher;
import cn.faifai.tagapi.dto.TestDTO;
import cn.faifai.tagapi.entity.User;
import cn.faifai.tagapi.dto.FileUrlDto;
import cn.faifai.tagapi.dto.PageQuery;
import cn.faifai.tagapi.entity.Tag;
import cn.faifai.tagapi.repository.TagRepository;
import cn.faifai.tagapi.repository.UserRepository;
import cn.faifai.tagapi.service.TagService;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.web.PagedModel;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController/*自带resoponseBody*/
public class testController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private TagService tagService;
    @Autowired
    private TagRepository tagRepository;
    @RequestMapping("/test/say")
    public String test(){
        return "hello";
    }

    @RequestMapping("/test/user")
    public List<User> queryUser(){
        return userRepository.findAll();
    }

    @RequestMapping("/test/tag")
    public PagedModel<Tag> queryTag(){
//        tagService.saveTag(new Tag());
        Page<Tag> tagListByParentId = tagService.getTagListByParentId(0l,new PageQuery().setPageNum(1).setPageSize(10));
        tagListByParentId.getContent().forEach(System.out::println);
        PagedModel<Tag> tagPagedModel = new PagedModel<>(tagListByParentId);
        return tagPagedModel;
    }
    @RequestMapping("/test/taglist")
    public List<Tag> queryTagList(){
        return tagRepository.findByParentId(0l);
    }

//    @RequestMapping("/test/inner")
//    public R<Object> inner(){
//        return
//    }
    @PostMapping("/proxy")
    public ResponseEntity<StreamingResponseBody> fetchAndStreamFile(@RequestBody FileUrlDto fileUrl) {
        System.out.println(fileUrl);
        String url = fileUrl.getFileUrl();
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法和其他必要的头信息
            con.setRequestMethod("GET");

            // 获取输入流
            InputStream inputStream = con.getInputStream();

            // 设置响应头和状态码
            HttpHeaders headers = new HttpHeaders();
            // 你可以从con.getHeaderFields()中获取头信息，并复制到headers中
            for (var entry: con.getHeaderFields().entrySet()){
                if (ObjectUtil.isNull(entry.getKey())){
                    continue;
                }
                headers.put(entry.getKey(),entry.getValue());
            }
            // 返回StreamingResponseBody，这是一个输出流的包装器
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(outputStream -> {
                        IOUtils.copy(inputStream, outputStream); // 使用Apache Commons 来复制流
                    });
        } catch (IOException e) {
            System.out.println("错误");
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }
    @GetMapping("/proxy/**")
    public  ResponseEntity<StreamingResponseBody> proxyUrlFile(HttpServletRequest request) throws IOException {
        String fullPath = request.getRequestURI();
        // 提取 /proxy 后面的路径
        String filePath = fullPath.substring(fullPath.indexOf("/proxy") + "/proxy".length());
        String prefix = " http://192.168.102.200:9001/vcom";
        String fileUrl = prefix + filePath;
        URL obj = new URL(fileUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

        // 获取输入流
        InputStream inputStream = con.getInputStream();
        HttpHeaders headers = new HttpHeaders();
        for (Map.Entry<String, List<String>> entry : con.getHeaderFields().entrySet()) {
            if (ObjectUtil.isNull(entry.getKey())) {
                continue;
            }
            headers.put(entry.getKey(), entry.getValue());
        }
        // 返回StreamingResponseBody，这是一个输出流的包装器
        return ResponseEntity.ok()
//            .contentType(MediaType.parseMediaType("multipart/form-data"))
                .headers(headers)
                .body(outputStream -> {
                    IOUtils.copy(inputStream, outputStream);
                });
    }

    @RequestMapping("/test/Long")
    public R Long() throws JsonProcessingException {
        TestDTO testDTO = new TestDTO();
        testDTO.setId(1888785585325543426l);
        testDTO.setCreateTime(LocalDateTime.now());
        testDTO.setUpdateTime(new Date());
        return R.ok(testDTO);
    }

    @GetMapping("/test/fileSystem")
    public R fileSystem() throws IOException {
        File[] files = File.listRoots();
        for (File file : files) {
            System.out.println(file.getPath());
        }
        String sid = SidFetcher.getSid();
        System.out.println(sid);
        return R.ok();
    }
}
